<template>
  <div class="data-table-container">
    <!-- 表格 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="data || []"
      :stripe="stripe"
      :border="border"
      :size="size"
      :height="height"
      :max-height="maxHeight"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      :row-class-name="rowClassName"
      :row-key="rowKey"
      :highlight-current-row="highlightCurrentRow"
      @selection-change="handleSelectionChange"
      @current-change="handleCurrentChange"
      @row-click="handleRowClick"
      @row-dblclick="handleRowDblClick"
      @sort-change="handleSortChange"
      @filter-change="handleFilterChange"
      class="data-table"
    >
      <!-- 复选框列 -->
      <el-table-column
        v-if="showSelection"
        type="selection"
        :reserve-selection="reserveSelection"
        width="50"
      />

      <!-- 索引列 -->
      <el-table-column
        v-if="showIndex"
        type="index"
        :index="customIndex"
        width="60"
        align="center"
      >
        <template #header>
          <el-checkbox v-model="selectAll" @change="handleSelectAll">
            {{ showIndex ? '序号' : '' }}
          </el-checkbox>
        </template>
      </el-table-column>

      <!-- 动态渲染列 -->
      <template v-for="(column, index) in columns" :key="index">
        <!-- 普通列 -->
        <el-table-column
          v-if="column.type !== 'expand'"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth"
          :align="column.align || 'center'"
          :sortable="column.sortable"
          :fixed="column.fixed"
          :show-overflow-tooltip="column.showOverflowTooltip !== false"
          :formatter="column.formatter"
          :filters="column.filters"
          :filter-multiple="column.filterMultiple !== false"
          :filter-method="column.filterMethod"
        >
          <!-- 自定义列内容 -->
          <template v-if="column.slot" #default="scope">
            <slot :name="column.slot" :row="scope.row" :column="column" :$index="scope.$index"></slot>
          </template>
          <!-- 直接渲染内容 -->
          <template v-else-if="column.render" #default="scope">
            {{ column.render(scope.row, column, scope.$index) }}
          </template>
        </el-table-column>

        <!-- 展开列 -->
        <el-table-column
          v-else-if="column.type === 'expand'"
          type="expand"
        >
          <template #default="scope">
            <slot :name="column.slot" :row="scope.row" :$index="scope.$index"></slot>
          </template>
        </el-table-column>
      </template>

      <!-- 操作列 -->
      <el-table-column
        v-if="showAction"
        label="操作"
        :width="actionWidth"
        :fixed="actionFixed"
        align="center"
      >
        <template #default="scope">
          <slot name="action" :row="scope.row" :$index="scope.$index"></slot>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="showPagination" class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.pageSizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :background="pagination.background"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && (!data || data.length === 0)" class="empty-state">
      <slot name="empty">
        <el-empty description="暂无数据" />
      </slot>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 定义组件的props
const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    default: () => []
  },
  // 表格列配置
  columns: {
    type: Array,
    required: true,
    default: () => []
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  },
  // 是否显示复选框
  showSelection: {
    type: Boolean,
    default: false
  },
  // 是否显示索引
  showIndex: {
    type: Boolean,
    default: false
  },
  // 是否显示操作列
  showAction: {
    type: Boolean,
    default: false
  },
  // 操作列宽度
  actionWidth: {
    type: [String, Number],
    default: 180
  },
  // 操作列是否固定
  actionFixed: {
    type: [Boolean, String],
    default: false
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true
  },
  // 分页配置
  pagination: {
    type: Object,
    default: () => ({
      current: 1,
      size: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      background: true
    })
  },
  // 是否为斑马纹
  stripe: {
    type: Boolean,
    default: true
  },
  // 是否带有边框
  border: {
    type: Boolean,
    default: false
  },
  // 表格大小
  size: {
    type: String,
    default: 'default',
    validator: (value) => {
      return ['large', 'default', 'small'].includes(value)
    }
  },
  // 表格高度
  height: {
    type: [String, Number],
    default: ''
  },
  // 表格最大高度
  maxHeight: {
    type: [String, Number],
    default: ''
  },
  // 表头样式
  headerCellStyle: {
    type: [Object, Function],
    default: () => ({})
  },
  // 单元格样式
  cellStyle: {
    type: [Object, Function],
    default: () => ({})
  },
  // 行类名
  rowClassName: {
    type: [String, Function],
    default: ''
  },
  // 行唯一标识
  rowKey: {
    type: [String, Function],
    default: ''
  },
  // 是否高亮当前行
  highlightCurrentRow: {
    type: Boolean,
    default: false
  },
  // 是否在数据更新之后保留之前选中的数据
  reserveSelection: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits([
  'selection-change',
  'current-change',
  'row-click',
  'row-dblclick',
  'sort-change',
  'filter-change',
  'size-change',
  'pagination-change'
])

// 表格引用
const tableRef = ref(null)

// 全选状态
const selectAll = ref(false)

// 自定义索引
function customIndex(index) {
  return (props.pagination.current - 1) * props.pagination.size + index + 1
}

// 处理全选
function handleSelectAll() {
  if (selectAll.value) {
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
  } else {
    if (tableRef.value) {
      props.data.forEach(row => {
        tableRef.value.toggleRowSelection(row, false)
      })
    }
  }
}

// 处理复选框选择变化
function handleSelectionChange(selection) {
  emit('selection-change', selection)
}

// 处理当前行变化
function handleCurrentChange(currentRow) {
  emit('current-change', currentRow)
}

// 处理行点击
function handleRowClick(row, column, event) {
  emit('row-click', row, column, event)
}

// 处理行双击
function handleRowDblClick(row, column, event) {
  emit('row-dblclick', row, column, event)
}

// 处理排序变化
function handleSortChange(column, prop, order) {
  emit('sort-change', column, prop, order)
}

// 处理筛选变化
function handleFilterChange(filters) {
  emit('filter-change', filters)
}

// 处理分页大小变化
function handleSizeChange(size) {
  emit('size-change', size)
  emit('pagination-change', { ...props.pagination, size })
}

// 处理分页当前页变化
function handleCurrentChange(current) {
  emit('pagination-change', { ...props.pagination, current })
}

// 暴露方法给父组件
defineExpose({
  tableRef,
  handleSelectAll,
  clearSelection: () => {
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
  },
  toggleRowSelection: (row, selected) => {
    if (tableRef.value) {
      tableRef.value.toggleRowSelection(row, selected)
    }
  },
  setCurrentRow: (row) => {
    if (tableRef.value) {
      tableRef.value.setCurrentRow(row)
    }
  },
  clearSort: () => {
    if (tableRef.value) {
      tableRef.value.clearSort()
    }
  },
  clearFilter: (columnKeys) => {
    if (tableRef.value) {
      tableRef.value.clearFilter(columnKeys)
    }
  },
  doLayout: () => {
    if (tableRef.value) {
      tableRef.value.doLayout()
    }
  },
  sort: (prop, order) => {
    if (tableRef.value) {
      tableRef.value.sort(prop, order)
    }
  }
})
</script>

<style scoped>
.data-table-container {
  background: #fff;
  border-radius: 4px;
  padding: 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.data-table {
  width: 100%;
}

.pagination-container {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-top: 1px solid #ebeef5;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}

:deep(.el-table__empty-text) {
  color: #909399;
  font-size: 14px;
}

:deep(.el-table__header-wrapper th) {
  background-color: #fafafa;
  font-weight: 500;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}

:deep(.el-table__row.current-row td) {
  background-color: #e6f7ff;
}
</style>